﻿using DevExpress.XtraLayout;
using System.Collections.Generic;
using System.ComponentModel;

namespace Inaction.UI.Settings
{
    public static class LayoutGroupSetting
    {
        public static void SetRootGroup()
        {
            LayoutGroup root = null;
            var components = ComponentCache.Components;
            foreach (var component in components)
            {
                if (component.Site != null && component.Site.Name == "Root")
                {
                    root = (LayoutGroup)component;
                    break;
                }
            }
            if (root != null)
            {
                LayoutGroupSetting.SetGroupControlTabIndex(root);
            }
        }
        public static void SetGroupControlTabIndex(LayoutGroup group)
        {
            List<LayoutItemContainer> list = new List<LayoutItemContainer>();
            foreach (var item in group.Items)
            {
                if (item is LayoutItemContainer)
                {
                    list.Add(item as LayoutItemContainer);
                }
            }
            int index = 0;
            foreach (var item in list)
            {
                if (item is LayoutGroup)
                {
                    SetLayoutGroup(item as LayoutGroup, ref index);
                }
                else if (item is TabbedControlGroup)
                {
                    SetTabbedGroup(item as TabbedControlGroup, ref index);
                }
            }
        }

        private static void SetLayoutGroup(LayoutGroup group, ref int index)
        {
            foreach (var item in group.Items)
            {
                if (item is LayoutControlItem)
                {
                    var layoutItem = item as LayoutControlItem;
                    if (layoutItem.Control == null) continue;
                    layoutItem.Control.TabIndex = index;
                    index++;
                }
            }
        }

        private static void SetTabbedGroup(TabbedControlGroup group, ref int index)
        {
            for (int i = 0; i < group.TabPages.Count; i++)
            {
                var item = group.TabPages[i];
                SetLayoutGroup(item as LayoutGroup, ref index);
            }
        }
    }
}